//
//  ZQHomeViewController.m
//  柳州微博
//
//  Created by Apple_Lzzy40 on 16/9/14.
//  Copyright © 2016年 Apple_Lzzy40. All rights reserved.
//

#import "ZQHomeViewController.h"
#import "ZQSearchBar.h"
#import "ZQDropdownMenu.h"
#import "ZQTitleMenuViewController.h"
#import "ZQAccountTool.h"
#import "ZQAccount.h"
#import "AFNetworking.h"
#import "ZQTilteButton.h"
#import "UIImageView+WebCache.h"
#import "ZQUser.h"
#import "MJExtension.h"
#import "ZQLoadMoreFoot.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "ZQStatueCell.h"
#import "ZQStatusFrame.h"

@interface ZQHomeViewController ()<ZQDropdownMenuDelegate>
/**
 *  微博数组，每个数组元素代表一条
 */
@property(nonatomic,strong)NSMutableArray * statusesFrame;
@end

@implementation ZQHomeViewController
//懒加载初始化
-(NSMutableArray *)statusesFrame
{
    if (_statusesFrame==nil) {
        _statusesFrame=[[NSMutableArray alloc] init];
    }
    return _statusesFrame;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置背影色
    self.tableView.backgroundColor=ZQColor(219, 219, 219);
    
    //1.设置导航栏内容
    [self setUpNavi];
    //2.获取服务器的用户信息（昵称）
    [self setUpserInfo];
    
    //3.获取服务器的最新微博信息
    //[self loadNewstatus];
    
    //4.下拉更新信息
    [self refreshNewstauts];
    
    //5.显示上拉控件
    [self setUpDownLoad];
    self.tableView.rowHeight = 150;
    
    //6.获取未读微博信息
    NSTimer * timer=[NSTimer scheduledTimerWithTimeInterval:8.0 target:self selector:@selector(setupUnreaCont) userInfo:nil repeats:YES];
    //把时钟添加到主线程
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
    
   }
/**
 *  加载未读微博数
 */
-(void)setupUnreaCont
{
    //1.创建管理者
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    //创建帐号实例
    ZQAccount * account =[ZQAccountTool account];
    
    params[@"access_token"]=account.access_token;
    params[@"uid"]=account.uid;
    
    //3.发送请求https://rm.api.weibo.com/2/remind/unread_count.json
    [manager GET :@"https://rm.api.weibo.com/2/remind/unread_count.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
        
//          NSLog(@" 获取服务器的微博信息 请求成功 返回数据%@",responseObject);
        
        int status=[responseObject[@"status"] intValue];
        //app徽章数字
            UIUserNotificationSettings * settings=[UIUserNotificationSettings  settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            
        if (status==0) {
            //tab徽章数字
            self.tabBarItem.badgeValue=nil;
            //app徽章数字
            [UIApplication sharedApplication].applicationIconBadgeNumber=0;
        }else
        {
            // tab 徽章数字
            self.tabBarItem.badgeValue=[NSString stringWithFormat:@"%d",status];
            //app徽章数字
            [UIApplication sharedApplication].applicationIconBadgeNumber=status;
            
            
            static int count=0;
            if (count!=status) {
                count=status;
                [self playPrompt];
            }
            
            
        }
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@" 请求失败%@",error);
        
    }];
    
    
    
    
}
//
-(void)playPrompt
{
    // 要播放的音频文件地址
    NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"4" ofType:@"wav"];
    
    
    NSURL *url = [NSURL fileURLWithPath:urlPath];
    
    // 声明需要播放的音频文件ID[unsigned long]
    SystemSoundID ID;
    
    // 创建系统声音，同时返回一个ID
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &ID);
    

  
}

/**
 *  显示上拉控件
 */
-(void)setUpDownLoad
{
    ZQLoadMoreFoot * footre=[ZQLoadMoreFoot footer];
    footre.backgroundColor=[UIColor grayColor];
    footre.hidden=YES;
    self.tableView.tableFooterView=footre;
}
/**
 *  下拉更新信息
 */
-(void)refreshNewstauts
{
    //1.创建下拉控件
    UIRefreshControl *refControl=[[UIRefreshControl alloc] init];
    [refControl addTarget:self action:@selector(refreshState:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refControl];
  
    //2.马上加载数据,相当于手动下拉
    [self refreshState:refControl];
    
}
/**
 *  下拉更新
 *
 *  @param control  当前的下拉控件
 */
-(void)refreshState:(UIRefreshControl *)control
{
//    NSLog(@"下拉更新信息");
    
    //1.创建管理者
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    //创建帐号实例
    ZQAccount * account =[ZQAccountTool account];
    
    params[@"access_token"]=account.access_token;
    //params[@"count"]=@10;
    
   ZQStatusFrame *firstStatusFrame= [self.statusesFrame firstObject];
    //最大微博ID
    params[@"since_id"]=firstStatusFrame.status.idstr;
    
    //3.发送请求https://api.weibo.com/2/statuses/friends_timeline.json
    [manager GET :@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
        
//       NSLog(@" 获取服务器的微博信息 请求成功 返回数据  配图%@",responseObject);
        
        // 从服务器返回的数据中，获取微博字典数组
        NSArray * tmpDictArray=responseObject[@"statuses"];
        //临时水桶
        NSArray * tmpArray=[ZQStatus objectArrayWithKeyValuesArray:tmpDictArray];
    
         //将ZQStatus 数组转成 ZQStatusFrame数组
        NSArray * statusesFrameArray=[self statusFrmaeWithStatuses:tmpArray];
        //NSArray *  statusesFrameArray = [self statusFrmaeWithStatuses:tmpArray];
        // 把水倒入水缸
        NSRange range=NSMakeRange(0, statusesFrameArray.count);
    
        NSIndexSet *set=[NSIndexSet indexSetWithIndexesInRange:range];
        
        [self.statusesFrame insertObjects:statusesFrameArray atIndexes:set];
        //重新刷新tableView
        [self.tableView reloadData];
        
        //显示下拉更新的微博数量
        [self showNewStatusCount:(int)statusesFrameArray.count];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@" 请求失败%@",error);
        
    }];

    
    [control endRefreshing];
}

//将ZQStatus 数组转成 ZQStatusFrame数组
-(NSArray *)statusFrmaeWithStatuses:(NSArray *)array
{
    NSMutableArray * stauesFrameArray=[NSMutableArray array];
    //将ZQStatus 数组转成 ZQStatusFrame数组
    for (ZQStatus * status in  array) {
        ZQStatusFrame * statusFeame=[[ZQStatusFrame alloc] init];
        statusFeame.status=status;
        [stauesFrameArray addObject:statusFeame];
    }
    return stauesFrameArray;
   
}

//细化每个cell 的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZQStatusFrame * statusFrame = self.statusesFrame[indexPath.row];
    return statusFrame.cellHeight;
}

 //显示下拉更新的微博数量
-(void)showNewStatusCount:(int)count
{
    //1.创建 label
    UILabel *label=[[UILabel alloc] init];
    label.width=[UIScreen mainScreen].bounds.size.width;
    label.height=30;
    UIImage *backImage=[UIImage imageNamed:@"timeline_new_status_background"];
    label.y=64-label.height;
    label.backgroundColor=[UIColor colorWithPatternImage:backImage];
    
    if (count==0) {
        label.text=@"没有新数据，请稍后再试！";
    }else
    {
    
        label.text=[NSString stringWithFormat:@"刷新%d条数据！",count];
        //居中
        label.textAlignment=NSTextAlignmentCenter;
    }
    //2.添加到导航栏下面
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    //3.动画
    CGFloat duration=0.2;
    [UIView animateWithDuration:duration animations:^{
        label.y=60;
    }completion:^(BOOL finished){
    
        //自我销毁
        [UIView animateWithDuration:0.5 animations:^{
            label.y=64-label.height;
            
        }completion:^(BOOL finished) {
            [label removeFromSuperview];
        }
         ];
    }
     ];
    //NSLog(@"刷新更新的数据tmpArray.count＝%d",count);
   
}
/**获取服务器的最新微博信息*/
-(void)loadNewstatus
{ 
    
    //1.创建管理者
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    //创建帐号实例
    ZQAccount * account =[ZQAccountTool account];
   
    params[@"access_token"]=account.access_token;
    //params[@"count"]=@1;
   
    //3.发送请求https://api.weibo.com/2/statuses/friends_timeline.json
    [manager GET :@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
        
       // NSLog(@" 获取服务器的微博信息 请求成功 返回数据%@",responseObject);
       // 从服务器返回的数据中，获取微博字典数组
        NSArray * tmpDictArray=responseObject[@"statuses"];
        
      [self.statusesFrame addObjectsFromArray:[ZQStatus objectArrayWithKeyValuesArray:tmpDictArray]];
        
        //重新刷新tableView
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@" 请求失败%@",error);
        
    }];

}

/**获取服务器的用户信息（昵称）*/
-(void)setUpserInfo
{
    //1.创建管理者
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    //创建帐号实例
    ZQAccount * account =[ZQAccountTool account];
    params[@"access_token"]=account.access_token;
    params[@"uid"]=account.uid;
        //3.发送请求https://api.weibo.com/2/users/show.json
    [manager GET :@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
        
      //  NSLog(@" 请求成功 返回数据%@",responseObject);
        
//        //从返回数据获取微博账号的名称
//        NSString * name = responseObject[@"name"];
        ZQUser * user=[ZQUser objectWithKeyValues:responseObject];
        NSString * name=user.name;
        //获取标题按钮
        UIButton * tilteButton=(UIButton *) self.navigationItem.titleView;
        
        //设置标题按钮的文本
        [tilteButton setTitle:name forState:UIControlStateNormal];
        
        //把名称赋给帐号模型

        account.name=user.name;
       
        //调用保存方法
        [ZQAccountTool saveAccount:account];
        
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@" 请求失败%@",error);
        
    }];
}
/**设置导航栏内容*/
-(void)setUpNavi
{
    //self.view.backgroundColor = [UIColor orangeColor];
    //设置导航栏左上角的按钮
    self.navigationItem.leftBarButtonItem=[UIBarButtonItem itemWithTarget:self action:@selector(friend) iamge:@"navigationbar_friendsearch"highLiightedImage:@"navigationbar_friendsearch_highlighted"];
   //设置导航栏右上角的按钮
    self.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithTarget:self action:@selector(pop) iamge:@"navigationbar_pop"highLiightedImage:@"navigationbar_pop_highlighted"];

     ZQTilteButton *titlButton=[[ZQTilteButton alloc]init ];
     titlButton.width=150;
     titlButton.height=30;
    
    ZQAccount * account =[ZQAccountTool account];
    NSString * name=account.name;
    if (name==nil) {
        name=@"首页";
    }
    [titlButton setTitle:name forState:UIControlStateNormal];
    //监听标题点击
    [titlButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //添加到导航栏中部
    self.navigationItem.titleView=titlButton;
}

-(void)dropdownMenu:(ZQDropdownMenu *) tabBar{
    UIButton * button = (UIButton *)self.navigationItem.titleView;
    button.selected = NO;
}

/**
 *  点击标题
 */
-(void)titleClick:(UIButton *)titlButton
{
    
    //1.创建下拉菜单
    ZQDropdownMenu * menu =[ZQDropdownMenu dropdownMenu];
    //2.设置菜单内容
    // 创建通讯录controller
    ZQTitleMenuViewController *vc =[[ZQTitleMenuViewController alloc]init];
    vc.view.height=50*3;
    menu.contentController=vc;
    
    menu.delegate = self;
    
    //3.菜单显示在指定位置
    [menu showAtView: titlButton];
    
   
    
   
}
/**
 *  contactAdd 按钮点击方法
 */
-(void)addClik
{
    NSLog(@"addClik!");
}

- (void)friend
{
    NSLog(@"friend!");
}
-(void)pop
{
    NSLog(@"pop!");
}
#pragma mark - Table view data source
//组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}
//每组的成员个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.statusesFrame.count;
}

//细化单元格
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    //创建自定义Cell
    ZQStatueCell * cell=[ZQStatueCell cellWithTabView:tableView];

    //把数据模型的具体数据赋值给Cell具体的对象
    cell.statusFrame=self.statusesFrame[indexPath.row];

     return cell;
 }

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
   //取出内容y
    CGFloat offsetY=scrollView.contentOffset.y;
    
    //内容高度和视图高度的差距
    CGFloat judgeFfsetY=scrollView.contentSize.height +scrollView.contentInset.bottom - scrollView.height-self.tableView.tableFooterView.height;
    
    //NSLog(@"offsteY  =%f   judgeFfsetY=%f"  ,offsetY,judgeFfsetY);
    //初始化的时候，微博为0，返回 或数据正在加载，返回
    if ((self.statusesFrame.count == 0) || (self.tableView.tableFooterView.hidden == NO)){
        return;
    }
   
    if ((offsetY>judgeFfsetY) ) {
        
        //显示页眉
        self.tableView.tableFooterView.hidden=NO;
        //加载数据
        [self loadMoreFooter];
       // NSLog(@"调用加载方法！");
    }
}
//上拉加载数据
-(void)loadMoreFooter
{
    
//    NSLog(@"调用加载方法！");
//    NSLog(@"上拉更新！");
    
    //1.创建管理者
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    //创建帐号实例
    ZQAccount * account =[ZQAccountTool account];
    
    params[@"access_token"]=account.access_token;
    params[@"count"]=@5;
    
    ZQStatusFrame *lasStatusFrame= [self.statusesFrame lastObject];
    //最小微博ID
    long long max_id=lasStatusFrame.status.idstr.longLongValue -  1;
    params[@"max_id"]=@(max_id);
    
    //3.发送请求https://api.weibo.com/2/statuses/friends_timeline.json
    [manager GET :@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
        
        // 从服务器返回的数据中，获取微博字典数组
        NSArray * tmpDictArray=responseObject[@"statuses"];
        //临时水桶
        NSArray * tmpArray=[ZQStatus objectArrayWithKeyValuesArray:tmpDictArray];
        
        //将ZQStatus 数组转成 ZQStatusFrame数组
        NSArray * statusesFrameArray=[self statusFrmaeWithStatuses:tmpArray];

        // 把水倒入水缸
        // 默认添加到末端
        [self.statusesFrame addObjectsFromArray:statusesFrameArray];

        //重新刷新tableView
        [self.tableView reloadData];
        
        //隐藏页脚
        self.tableView.tableFooterView.hidden=YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@" 请求失败%@",error);
        
    }];
    
    


}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
